package com.shopping.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.common.utils.Constant;
import com.shopping.common.utils.PageUtils;
import com.shopping.common.utils.Query;
import com.shopping.product.dao.SkuInfoDao;
import com.shopping.product.entity.SkuImagesEntity;
import com.shopping.product.entity.SkuInfoEntity;
import com.shopping.product.entity.SpuInfoDescEntity;
import com.shopping.product.service.SkuImagesService;
import com.shopping.product.service.SkuInfoService;
import com.shopping.product.service.SkuSaleAttrValueService;
import com.shopping.product.service.SpuInfoDescService;
import com.shopping.product.vo.SkuItemVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Resource
    SkuImagesService skuImagesService;

    @Resource
    SpuInfoDescService spuInfoDescService;

    @Resource
    AttrGroupServiceImpl attrGroupService;

    @Resource
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("sku_id", key).or().like("sku_id", key));
        }
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !Constant.SEARCH_IGNORE_VALUE_ZERO.equals(catelogId)) {
            //todo 又是一个catalog
            wrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !Constant.SEARCH_IGNORE_VALUE_ZERO.equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }
        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max)) {
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                BigDecimal zero = new BigDecimal(0);
                if (bigDecimal.compareTo(zero) > 0) {
                    wrapper.le("price", max);
                }
            } catch (Exception e) {
                log.error(e.toString());
            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("spu_id", spuId);
        return this.list(wrapper);
    }

    /**
     * 获得商品详情
     * 由于商品基本信息和图片是同时进行的
     *
     * @param skuId skuId
     * @return
     */
    @Override
    public SkuItemVo getSkuItem(Long skuId) {
        long l = System.currentTimeMillis();
        SkuItemVo vo = new SkuItemVo();
        // 商品基本信息
        CompletableFuture<SkuInfoEntity> infoFuture = CompletableFuture.supplyAsync(() -> {
            SkuInfoEntity info = this.getById(skuId);
            // info判空
            vo.setInfo(info);
            return info;
        }, executor);

        // 图片
        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            QueryWrapper<SkuImagesEntity> imgWrapper = new QueryWrapper<>();
            imgWrapper.eq("sku_id", skuId);
            List<SkuImagesEntity> images = skuImagesService.list(imgWrapper);
            vo.setImages(images);
        }, executor);

        // spu销售属性组合
        CompletableFuture<Void> saleAttrFuture = infoFuture.thenAcceptAsync(res -> {
            if (res != null) {
                List<SkuItemVo.SkuItemSaleAttrVo> saleAttrs = skuSaleAttrValueService.getSaleAttrsBySpuId(res.getSpuId());
                vo.setSaleAttr(saleAttrs);
            }
        }, executor);
        // spu介绍
        CompletableFuture<Void> descFuture = infoFuture.thenAcceptAsync(res -> {
            if (res != null) {
                SpuInfoDescEntity spuInfo = spuInfoDescService.getById(res.getSpuId());
                vo.setDesc(spuInfo);
            }
        }, executor);

        // spu规格参数
        CompletableFuture<Void> baseAttrFuture = infoFuture.thenAcceptAsync(res -> {
            if (res != null) {
                List<SkuItemVo.SpuItemGroupAttrVo> itemGroupAttrVos = attrGroupService.getAttrGroupWithAttrsBySpuIdAndCatelogId(res.getSpuId(), res.getCatalogId());
                vo.setGroupAttrs(itemGroupAttrVos);
            }
        }, executor);

        try {
            CompletableFuture.allOf(imgFuture, saleAttrFuture, descFuture, baseAttrFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        long l1 = System.currentTimeMillis();
        System.out.println("并行用时: = " + (l1 - l) + "ms");
        return vo;
    }


}
